
Page({
  data: {
    message:[], //详情信息
    imageUrls:[], //房间图片
    messageImg:[], //详情图片
    allcoupon:[],  //优惠券
    user_id:'',
    checkInDate:'',
    checkOutDate:'',
    token:'',
    openid:'',
    name: '',
    phone: '',
    stay:0,
    showModalFlag: false,  // 控制弹窗显示和隐藏
    animation: {},  // 存放动画
    price:0,
    checkedIndex:null,
    order_id:''
  },
  getuserinfo:function () { //获取用户表里的电话和姓名
    var that =this
    wx.request({
      url: `http://hotel.ttt:3007/protected/getuserinfo/${this.data.openid}`,
      method:'GET',
      header:{
        'Authorization': that.data.token 
      },
      success(res) {
        console.log("用户表姓名电话是否为空：",res.data.data[0].full_name==='');
        that.setData({
          user_id:res.data.data[0].user_id,
          name:res.data.data[0].full_name,
          phone:res.data.data[0].phone_number,
        })
      }
    })
  },
  onNameInput(e) {  //获取姓名
    this.setData({
      name: e.detail.value
    });
  },
  onPhoneInput(e) { //获取电话
    this.setData({
      phone: e.detail.value
    });
  },
  onSubmit:function(x,y) { //提交表单
    //const { name, phone } = e.detail.value;
    //console.log(e.detail.value)
    // 校验电话是否符合标准
    const phoneRegex = /^1[3-9]\d{9}$/;  // 手机号正则表达式
    if (!x || !phoneRegex.test(y)){
      wx.showToast({
        title: '请填写正确信息',
        icon: 'none'
      });
      return;
    }
  },
 
  getDaysBetween(inDate,outDate){ //一共住几天
    let startDate = Date.parse(inDate);
    let endDate = Date.parse(outDate);
    let days=(endDate - startDate)/(1*24*60*60*1000);
    return  days;
  },

  showModal:function () { // 显示弹窗
    var that =this
    // 获取房间图片
    wx.request({
      url: `http://hotel.ttt:3007/api/getImages/${this.data.message.room_id}`, 
      success(res) {
        // 在小程序页面展示这些图片
        that.setData({
          imageUrls: res.data.data
        });
      }
    });
    // 获取房间详情图片
    wx.request({
      url: `http://hotel.ttt:3007/api/getMessage/${this.data.message.room_id}`, 
      success(res) {
        // 在小程序页面展示这些图片
        that.setData({
          messageImg: res.data.data
        });
      }
    })
    const animation = wx.createAnimation({
      duration: 5000,  // 动画持续时间
      timingFunction: 'ease-in-out'  // 动画过渡方式
    });

    // 让弹窗从屏幕外部（底部）滑入
    animation.translateY(-500).step(); // 初始位置在屏幕底部外500px

    that.setData({
      showModalFlag: true,
      animation: animation.export()
    });

    // 延时滑动到屏幕底部
    setTimeout(() => {
      const slideInAnimation = wx.createAnimation({
        duration: 300,
        timingFunction: 'ease-in-out'
      });

      // 弹窗滑动到屏幕底部
      slideInAnimation.translateY(0).step();

      this.setData({
        animation: slideInAnimation.export()
      });
    }, 300);  // 延时执行
  },
  closeModal:function() {  // 关闭弹窗
    const animation = wx.createAnimation({
      duration:300,
      timingFunction: 'ease-in-out'
    });

    // 弹窗滑动到屏幕下方
    animation.translateY(500).step();

    this.setData({
      animation: animation.export()
    });

    // 动画结束后隐藏弹窗
    setTimeout(() => {
      this.setData({
        showModalFlag: false
      });
    }, 300); // 动画持续时间后隐藏
  },

  getAllcoupon:function () { //获取优惠券
    var that =this
    wx.request({
      url: 'http://hotel.ttt:3007/protected/coupons',
      method: 'GET',
      header: {
        'Authorization': that.data.token// 将 token 添加到请求头
      },
      success: function (res) {
        if (res.data.success) {
          that.setData({
            allcoupon: res.data.data
          })
        } else {
          console.error('访问失败:', res.data.message);
        } 
      },
      fail: function (err) {
        console.error('请求失败:', err);
      }
    });
  },

  onRadioChange:function (e) { //使用优惠券后的价格
    let coupon_id = parseInt(e.detail.value)
    const res = this.data.allcoupon.find((r)=>r.coupon_id=== coupon_id)
    if(parseFloat(this.data.message.price) >= res.coupon_name && res.discount>1){
      let price = parseFloat(this.data.message.price) - res.discount
      this.setData({
        price:price
      })
      console.log(e.detail.value,coupon_id,this.data.message.price,price);
    }else if(parseFloat(this.data.message.price) >= res.coupon_name && res.discount<1){
      let price = parseFloat(this.data.message.price) * res.discount
      this.setData({
        price:price
      })
    }else{
      this.setData({
        price:this.data.message.price,
        checkedIndex:this.data.allcoupon.length+1
      })
    }
  }, 
  
     /*  for(var i=0;i<this.data.allcoupon.length;i++){
      if(coupon_id===i && parseFloat(this.data.message.price) >= this.data.allcoupon[coupon_id].coupon_name && this.data.allcoupon[coupon_id].discount>1){
      let price = parseFloat(this.data.message.price) - this.data.allcoupon[coupon_id].discount
      this.setData({
        price:price,
        //isshow:true,
        checkedIndex:coupon_id+1
      })
      return
    }else{
      this.setData({
        price:parseFloat(this.data.message.price),
        checkedIndex:coupon_id+10
      })
    };
    if(coupon_id===i&&parseFloat(this.data.message.price)>=this.data.allcoupon[coupon_id].coupon_name&&this.data.allcoupon[coupon_id].discount<1){
      let price = parseFloat(this.data.message.price)*this.data.allcoupon[coupon_id].discount
      this.setData({
        price:price,
        checkedIndex:coupon_id+1
      })
      return;
    }else{
      this.setData({
        price:parseFloat(this.data.message.price),  
        checkedIndex:coupon_id+10
      })
    }
  }
},  */
  createOrders:function(){
    var that =this
    wx.request({
      url: 'http://hotel.ttt:3007/protected/createOrders',
      method:"POST",
      header:{
        'Authorization': that.data.token// 将 token 添加到请求头
      },
      data: {
        user_id: that.data.user_id,
        room_id: that.data.message.room_id,
        check_in_date:that.data.checkInDate,
        check_out_date:that.data.checkOutDate,
        total_price:that.data.price
      },
      success: function (res) {
        if(res.data.message!='数据插入失败'){
          console.log(res.data);
          that.getOrderId()
        }else{
        console.log(res.data.message);}
      },
      fail: function (err) {
        console.error('请求失败:', err);
      }
    })
  },
  getOrderId:function(){
    var that =this
    wx.request({  //查讯待支付订单id
      url: `http://hotel.ttt:3007/protected/getorderId/${this.data.message.room_id}/${this.data.user_id}`,  // 动态拼接 URL
      method: 'GET',  // 请求方法是 GET
      header:{
        'Authorization': this.data.token// 将 token 添加到请求头
      },
      success: function(res) {
        if (res.data.success) {
          that.setData({
            order_id: res.data.data[0].order_id
          })
          console.log('查询成功，返回的数据:', res.data.data[0]);
        } else {
          console.log('查询失败，消息:', res.data.message);
        }
      },
      fail: function(error) {
        console.log('请求失败:', error);
      }
    });
  },
  form:function () {
    var that =this
    if(that.data.name!='' && that.data.phone!=''){
      that.onSubmit(that.data.name,that.data.phone)
    }
    if(that.data.name==='' && that.data.phone===''){
    wx.request({
      url: 'http://hotel.ttt:3007/protected/form',
      method: 'post',
      header: {
        'Authorization': that.data.token // 将 token 添加到请求头
      },
      data: {
        name:that.data.name,
        phone:that.data.phone,
        openid:that.data.openid    // 将数据发送到后端
      },
      success: function (res) {
        console.log(res)
        if (res.data.success) {
          console.log('访问成功:', res.data);
        } else {
          console.error('访问失败:', res.data);
        }
      },
      fail: function (err) {
        console.error('请求失败:', err);
      }
    });
  }
  },
  wxpay:function () {
    var that =this
    // 获取微信支付预支付订单
    wx.request({
      url: 'http://hotel.ttt:3007/protected/create-order', 
      method: 'POST',
      header:{
        'Authorization': that.data.token// 将 token 添加到请求头
      },
      data: {
        openid: that.data.openid,  // 用户的openid
        totalFee: 0.01,  // 支付金额（单位：分）
        body: '商品描述',  // 商品描述
      },
      success: function (res) {
        if (res.data.success) {
          const prepayId = res.data.prepay_id;
          const params = res.data.params;
          console.log(prepayId,params)
          // 调用微信支付接口
          wx.showModal({
            title: '提示',  // 弹窗的标题
            content: `请支付房费￥${that.data.price}`,  // 弹窗的内容
            showCancel: true,  // 是否显示取消按钮，默认为 true
            cancelText: '取消',  // 取消按钮的文字
            confirmText: '支付',  // 确定按钮的文字
            success(res) {
              if (res.confirm) {
                let btn =1
                // 用户点击了确定
                console.log('用户点击了确定');
               that.payment(true,prepayId)//插入一条支付订单记录
               that.orderStatus('paid','confirmed',that.data.order_id) //更改订单状态为已支付
               //修改房间状态
               that.updataRoomStatus('booked')
               // 使用 setTimeout 实现2秒后跳转
               wx.showLoading({
                title: '加载中...',
                mask: true // 遮罩层，防止用户点击其它区域
              });
              setTimeout(() => {
                wx.hideLoading();// 隐藏 loading 提示框 
                wx.navigateTo({
                  url: '/pageB/pages/loading/loading?btn='+btn+'&order_id='+that.data.order_id,
                });
              }, 2000);
              } else if (res.cancel) {
                // 用户点击了取消
                let btn = 0
                console.log('用户点击了取消');
                that.payment(false,prepayId)
                that.orderStatus('pending','confirmed',that.data.order_id)//更改订单状态为待支付
                wx.navigateTo({
                  url: '/pageB/pages/loading/loading?btn='+btn+'&order_id='+that.data.order_id,
                })
              }
            },
            fail(err) {
              // 弹窗调用失败时的回调
              console.error('弹窗失败', err);
            }
          });
        }
      }
    });
  },
  updataRoomStatus:function(e){
    var that =this
    wx.request({
      url: `http://hotel.ttt:3007/api/usedRoom/${e}/${that.data.message.room_id}`,
      method: 'post',  // 请求方法是 GET
      success:function(res){
        if(res.data.success) console.log('更新房间状态成功');
        else console.log('更新房间状态失败');
      },fail:function(err){
        console.log(err);
      }
    })
  },
  payment:function (status,prepayId) {
    var that =this
    wx.request({
      url: 'http://hotel.ttt:3007/protected/payment',
      method: 'post',  // 请求方法是 GET
      header:{
        'Authorization': that.data.token// 将 token 添加到请求头
      },
      data:{
        status:status,
        order_id:that.data.order_id,
        amount:that.data.price,
        payment_method:'wechat',
        transaction_id:prepayId
      },
      success: function (res) {
        if(res.data.success){
          console.log('成功插入支付订单记录',res)
        }else{
          console.log('插入支付订单记录失败',res)
        }
      },
      fail:function(err){
        console.log(err.data);
      }
    })
  },
  orderStatus:function(payment_status, order_status, order_id ){
    wx.request({
      url: 'http://hotel.ttt:3007/protected/usedOrder',
      method: 'post',  // 请求方法是 GET
      header:{
        'Authorization': this.data.token// 将 token 添加到请求头
      },
      data:{
        payment_status, order_status, order_id 
      },
      success: function (res) {
        console.log(res.data.message)
      },
      fail: function (err) {
        console.error('请求失败:', err);
      }
    })
  },
  gotoPay:function () { //提交表单，支付
    var that =this
    that.form()
    that.createOrders() //创建一条订单记录 状态是待支付
    that.wxpay() 
  },
  /**
   * 生命周期函数--监听页面加载
   */ 
  onLoad(options) {
    let token = wx.getStorageSync("token");
    let openid=wx.getStorageSync("openid")  
    let message = options
    this.setData({
      message,token,openid,
      price:message.price
    })
    this.getAllcoupon()
    this.getuserinfo()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let ddd=wx.getStorageSync('ROOM_SOURCE_DATE')
    console.log(ddd)
    var stay = this.getDaysBetween(ddd.checkInDate, ddd.checkOutDate)  
    this.setData({
      checkInDate:ddd.checkInDate,
      checkOutDate:ddd.checkOutDate,
      stay:stay
    })
    console.log(this.data.checkInDate,this.data.checkOutDate,stay)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})